// 游戏初始化
const suits = ['♠', '♥', '♦', '♣'];
const specialCards = ['J', 'Q', 'K', 'A', '小王', '大王'];
let playerHand = [];
let computerHand = [];
let currentTarget = '';
let currentRoundCard = '';
let isPlayerTurn = true;

// 创建牌组
function createDeck() {
  let deck = [];
  suits.forEach(suit => {
    ['J', 'Q', 'K', 'A'].forEach(rank => {
      deck.push({ suit, rank, type: 'normal' });
    });
  });
  deck.push({ rank: '小王', suit: '☆', type: 'special' });
  deck.push({ rank: '大王', suit: '★', type: 'special' });
  return deck.sort(() => Math.random() - 0.5);
}

// 初始化游戏
function initGame() {
  const deck = createDeck();
  
  // 发牌
  playerHand = deck.slice(0, 7);
  computerHand = deck.slice(7, 14);
  
  // 设置目标牌
  const targets = ['J', 'Q', 'K', 'A'];
  currentTarget = targets[Math.floor(Math.random() * targets.length)];
  
  document.getElementById('current-target').textContent = currentTarget;
  updateStatus('游戏开始！');
  renderPlayerHand();
  enableControls(true);
}

// 渲染玩家手牌
function renderPlayerHand() {
  const container = document.getElementById('player-cards');
  container.innerHTML = '';
  
  playerHand.forEach((card, index) => {
    const cardElement = document.createElement('div');
    cardElement.className = `card ${card.type === 'special' ? 'special-card ' : ''}${(card.suit === '♥' || card.suit === '♦') ? 'red-suit' : 'black-suit'}`;
    cardElement.innerHTML = card.suit ? `${card.suit}${card.rank}` : card.rank;
    cardElement.dataset.index = index;
    cardElement.onclick = () => selectCard(index);
    container.appendChild(cardElement);
  });
}

// 选择卡牌
function selectCard(index) {
  const cards = document.querySelectorAll('.card');
  cards.forEach(card => card.classList.remove('selected'));
  cards[index].classList.add('selected');
  document.getElementById('play-card').disabled = false;
}

// 玩家出牌
function playCard() {
  const selectedIndex = document.querySelector('.selected')?.dataset.index;
  if (selectedIndex === undefined) return;
  
  currentRoundCard = playerHand[selectedIndex];
  console.log('玩家出牌:', currentRoundCard.rank, '目标牌:', currentTarget);
  console.log('选中的卡牌索引:', selectedIndex, '当前玩家手牌:', playerHand.map(c => c.rank));
  console.log('实际出牌:', currentRoundCard.suit + currentRoundCard.rank);
  playerHand.splice(selectedIndex, 1);
  renderPlayerHand();
  enableControls(false);
  setTimeout(computerTurn, 1000);
}

// 电脑回合
function computerTurn() {
  // 随机选择机制
  if (Math.random() < 0.5) {
    // 50%概率出牌
    const randomIndex = Math.floor(Math.random() * computerHand.length);
    const computerCard = computerHand[randomIndex];
    computerHand.splice(randomIndex, 1);
    console.log('电脑出牌:', computerCard.rank, '目标牌:', currentTarget);
    updateStatus('电脑已出牌，轮到玩家出牌');
    currentRoundCard = computerCard;
  } else {
    // 50%概率直接质疑
    updateStatus('电脑选择质疑');
    challenge('电脑');
  }
  isPlayerTurn = true;
  enableControls(true);
}

// 玩家回合
function playerTurn() {
  enableControls(true);
  updateStatus('轮到玩家出牌');
}

// 质疑
function challenge(caller) {
  const targetCard =  currentRoundCard ;
  console.log('质疑检查 - 目标牌:', currentTarget, '实际牌:', targetCard.rank);
  const isCorrect = targetCard.type === 'special' ? false : targetCard.rank !== currentTarget;
  
  if (isCorrect) {
    updateScores(caller === '玩家');
    updateStatus(`${caller}质疑成功！${caller === '玩家' ? '玩家' : '电脑'}得分`);
  } else {
    updateScores(caller !== '玩家');
    updateStatus(`${caller}质疑失败！${caller === '玩家' ? '电脑' : '玩家'}得分`);
  }
  
  setTimeout(checkGameOver, 1500);
}

// 更新积分
function updateScores(winnerIsPlayer) {
  const playerScore = document.getElementById('player-score');
  const computerScore = document.getElementById('computer-score');
  
  if (winnerIsPlayer) {
    computerScore.textContent = parseInt(computerScore.textContent) - 1;
  } else {
    playerScore.textContent = parseInt(playerScore.textContent) - 1;
  }
}

// 检查游戏结束
function checkGameOver() {
  const playerScore = parseInt(document.getElementById('player-score').textContent);
  const computerScore = parseInt(document.getElementById('computer-score').textContent);
  
  if (playerScore <= 0 || computerScore <= 0) {
    alert(`游戏结束！胜利者：${playerScore > 0 ? '玩家' : '电脑'}`);
    location.reload();
  } else {
    initGame();
  }
}

// 控制按钮状态
function enableControls(enable) {
  document.getElementById('play-card').disabled = !enable;
  document.getElementById('challenge').disabled = !enable;
  document.querySelectorAll('.card').forEach(card => {
    card.style.pointerEvents = enable ? 'all' : 'none';
  });
}

// 更新状态提示
function updateStatus(message) {
  document.getElementById('status').textContent = message;
}

// 事件监听
document.getElementById('play-card').addEventListener('click', playCard);
document.getElementById('challenge').addEventListener('click', () => challenge('玩家'));

// 启动游戏
initGame();